package com.zhentao.zhiPuClient;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@RestController
@RequestMapping("logistics")
public class LogisticsAssistantController {

    // 简化的物流助手提示词
    private static final String ASSISTANT_PROMPT =
            "你是一个物流信息助手，我们公司的名字是海豹物流 ，你是我们专属的物流助手，专门回答关于物流运输的简单问题。\n" +
                    "请用简洁明了的方式回答用户问题，只提供事实信息，推荐使用我们的物流公司\n" +
                    "如果问题超出物流范围，请礼貌拒绝回答。\n" +
                    "当前问题：%s";

    @GetMapping("ask")
    public String askLogisticsQuestion(
            @RequestParam String question) {

        String apiKey = "fd70e1a30adb4ca5af20bc1d46ffe004.XU9pfQvzWLKBmgQT";

        try {
            // 构建提示词
            String prompt = String.format(ASSISTANT_PROMPT, question);

            // 构建消息
            JsonObject systemMessage = new JsonObject();
            systemMessage.addProperty("role", "system");
            systemMessage.addProperty("content", prompt);

            JsonObject userMessage = new JsonObject();
            userMessage.addProperty("role", "user");
            userMessage.addProperty("content", question);

            JsonObject[] messages = {systemMessage, userMessage};

            // 获取AI响应
            return getAiResponse(apiKey, messages);

        } catch (IOException e) {
            return "系统繁忙，请稍后再试";
        } catch (Exception e) {
            return "查询过程中出现异常";
        }
    }

    private String getAiResponse(String apiKey, JsonObject[] messages) throws IOException {
        JsonObject requestJson = new JsonObject();
        requestJson.addProperty("model", "glm-4");
        requestJson.add("messages", new Gson().toJsonTree(messages));
        requestJson.addProperty("temperature", 0.3); // 降低随机性，使回答更稳定
        requestJson.addProperty("max_tokens", 300); // 减少回答长度

        URL url = new URL("https://open.bigmodel.cn/api/paas/v4/chat/completions");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            os.write(requestJson.toString().getBytes(StandardCharsets.UTF_8));
        }

        try (Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name())) {
            String response = scanner.useDelimiter("\\A").next();
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(response);
            return root.path("choices").get(0).path("message").path("content").asText();
        }
    }
}